<?

abstract class bf_http {

	protected $opts;

	public function __construct($options = array()) {
		$this->opts = array_merge(array(
			'timeout' => 3
		), $options);
	}

	public function escape($value) {
		return urlencode($value);
	}

	public function unescape($value) {
		return urldecode($value);
	}

	public function build_params($params) {
		return http_build_query($params);
	}

	public function disable_caching() {
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");
	}

	public function redirect($url) {
		header("Location: $url", true);
		exit(0);
	}

	public function download($options = array()) {

		if (!is_array($options))
			$options = array('location' => $options);

		$opts = array_merge(array(
			'location' => 'data/download.zip',
			'filename' => false,
			'content-type' => 'application/force-download',
			'content-length' => false,
			'block-size' => 8*1024,
		), $options);

		if ($opts['filename'] === false)
			$opts['filename'] = basename($opts['location']);

		if ($opts['content-length'] === false)
			$opts['content-length'] = filesize($opts['location']);

		if (!($fp = fopen($opts['location'], 'rb'))) {
			header('HTTP/1.1 404 File Not Found', true);
			return false;
		}
		
		header("Content-Type: {$opts['content-type']}"); 
		header("Content-Length: {$opts['content-length']}"); 
		header("Content-Disposition: attachment; filename=\"" . str_replace('"', '', $opts['filename']) . "\"");
		
		$seek_start = 0;
		$seek_end = $opts['content-length'] - 1;
		
		fseek($fp, $seek_start, SEEK_SET);
		$range_size = ($seek_end - $seek_start + 1);
		for ($block_size = $opts['block-size'], $readed = 0; $readed < $range_size; $readed += $block_size) {
			echo fread($fp, $block_size);
			$block_size = ($readed + $block_size > $range_size ? $range_size - $readed : $block_size);
		}

		fclose($fp);

		return true;
	}

	abstract public function get($url, $params = array(), $auth = array());
	abstract public function post($url, $params = array(), $auth = array());
}

?>